﻿using AutoMapper;
using B.S.BsicData.Api.Writer.Application.Command;
using B.S.BsicData.Domain;
using B.S.BsicData.ErrorCode.Entity;
using B.S.BsicData.Infartrans;
using MediatR;

namespace B.S.BsicData.Api.Writer.Application.CommandHandler
{
    public class CreateWhouseCommandHandler : IRequestHandler<CreateWhouseCommand, WHouseModeles>
    {
      
        private readonly IBaseReository<WHouseModeles> _warehouseRepository;
        private readonly IBaseReository<LocationModeles> _locationRepository;
        private readonly IBaseReository<WHouseLocationModel> _whouseLocationRepository;

        public CreateWhouseCommandHandler(
            IBaseReository<WHouseModeles> warehouseRepository,
            IBaseReository<LocationModeles> locationRepository,
            IBaseReository<WHouseLocationModel> whouseLocationRepository)
        {
            if (warehouseRepository == null)
            {
                Console.WriteLine("warehouseRepository is null");
            }
            if (locationRepository == null)
            {
                Console.WriteLine("locationRepository is null");
            }
            if (whouseLocationRepository == null)
            {
                Console.WriteLine("whouseLocationRepository is null");
            }
            _warehouseRepository = warehouseRepository;
            _locationRepository = locationRepository;
            _whouseLocationRepository = whouseLocationRepository;
        }

        public async Task<WHouseModeles> Handle(CreateWhouseCommand request, CancellationToken cancellationToken)
        {
            // 添加仓库
            var addedWarehouse = await _warehouseRepository.AddAsyncdesc(request.Warehouse);

            // 遍历要添加的库位列表
            foreach (var location in request.Locations)
            {
                // 添加库位
                var addedLocation = await _locationRepository.AddAsyncdesc(location);

                // 创建仓库库位关系实体
                var whouseLocation = new WHouseLocationModel
                {
                    WhouseID = addedWarehouse.WhouseID,
                    LocationID = addedLocation.LocationID
                };

                // 添加仓库库位关系
                await _whouseLocationRepository.AddAsync(whouseLocation);
            }
            // 保存所有更改
            await _warehouseRepository.SaveChangesAsync();

            return addedWarehouse;
        }
    }
    
}
